﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Slaughter;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Slaughter
{
    public class CreateSlaughtersCommendHandlers : IRequestHandler<CreateSlaughtersCommends, APIResult<Slaughters>>
    {

        private readonly IBaseRepository<Slaughters> slaughterRepository;
        private readonly IMapper mapper;

        public CreateSlaughtersCommendHandlers(IBaseRepository<Slaughters> slaughterRepository, IMapper mapper)
        {
            this.slaughterRepository = slaughterRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加屠宰信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Slaughters>> Handle(CreateSlaughtersCommends request, CancellationToken cancellationToken)
        {
            APIResult<Slaughters> result = new APIResult<Slaughters>();


            var exit = slaughterRepository.GetAllAsync().Result.FirstOrDefault(x => x.SlaughterId == request.SlaughterId);
            if (exit == null)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";

                var farm = mapper.Map<Slaughters>(request);
                farm.BatchId = request.BatchId;
                farm.IsDel = false;
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                await slaughterRepository.Add(farm);

            }
            else
            {
                mapper.Map(request, exit);

                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功";


                await slaughterRepository.Update(exit);
            }
       
        
            return await Task.FromResult(result);
        


           
            

        
        }
    }
}
